import { Config, Inject, Provide } from '@midwayjs/decorator';
import { BaseService, CoolCommException } from '@cool-midway/core';
import { InjectEntityModel } from '@midwayjs/typeorm';
import { Repository } from 'typeorm';
import { UserInfoEntity } from '../entity/info';
import { UserAdEntity } from '../entity/ad';
import { Context } from '@midwayjs/koa';
import * as moment from 'moment';
/**
 * 广告播放
 */
@Provide()
export class UserAdService extends BaseService {

  @InjectEntityModel(UserAdEntity)
  userAdEntity: Repository<UserAdEntity>;

  @InjectEntityModel(UserInfoEntity)
  userInfoEntity: Repository<UserInfoEntity>;

  @Inject()
  ctx: Context;

  /**
  * 判断需不需要观看广告
  */
  async advertisingPermission() {
    let permission = true
    let info = await this.userInfoEntity.findOneBy({ id: this.ctx.user.id })
    if (info.adViewing == 1) {
      permission = false
    }
    // 如果当前时间减去最后一次看广告的时间大于65,代表超过一小时了,要看广告
    if (info.adTime) {
      // 计算相差分钟数
      const minutesDifference = moment().diff(moment(info.adTime), 'minutes');
      if (minutesDifference <= 65) {
        permission = false
      }
    }
    return permission
  }

  async add(param) {
    if(param.status!=0){
      await this.userInfoEntity.update({ id: this.ctx.user.id }, { adTime: new Date() });
    }
    return await super.add(param)
  }
}
